package com.lll.simple.rpc.consumer;

import com.lll.simple.rpc.common.RpcProtocol;
import com.lll.simple.rpc.common.RpcRequest;
import com.lll.simple.rpc.common.RpcServiceHelper;
import com.lll.simple.rpc.common.ServiceMeta;
import com.lll.simple.rpc.protocol.decoder.RpcDecoder;
import com.lll.simple.rpc.protocol.encoder.RpcEncoder;
import com.lll.simple.rpc.protocol.handler.RpcHeartBeatHandler;
import com.lll.simple.rpc.protocol.handler.RpcResponseHandler;
import com.lll.simple.rpc.registry.RegistryService;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import lombok.extern.slf4j.Slf4j;

/**
 * @Author: liull
 * @Description:
 * @Date: Created in 17:35 2021/2/3
 * @Modified By:
 */
@Slf4j
public class RpcConsumer {

    private Bootstrap bootstrap;

    private EventLoopGroup eventLoopGroup;

    public RpcConsumer() {
        bootstrap = new Bootstrap();
        eventLoopGroup = new NioEventLoopGroup(4);
        bootstrap.group(eventLoopGroup).channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        socketChannel.pipeline()
                                .addLast(new RpcHeartBeatHandler())
                                .addLast(new RpcEncoder())
                                .addLast(new RpcDecoder())
                                .addLast(new RpcResponseHandler());
                    }
                })
                .option(ChannelOption.SO_KEEPALIVE, true);
    }

    public void sendRequest(RpcProtocol<RpcRequest> protocol, RegistryService registryService) throws Exception {
        RpcRequest request = protocol.getBody();
        Object[] params = request.getParams();
        String serviceKey = RpcServiceHelper.buildServiceKey(request.getClassName(), request.getServiceVersion());
        int hashCode = params.length > 0 ? params[0].hashCode() : serviceKey.hashCode();
        // 服务发现，找到要调用的服务
        ServiceMeta serviceMeta = registryService.discovery(serviceKey, hashCode);
        if (serviceMeta != null) {
            ChannelFuture future = bootstrap.connect(serviceMeta.getServiceAddr(), serviceMeta.getServicePort()).sync();
            future.addListener((ChannelFutureListener) arg0 -> {
                if (future.isSuccess()) {
                    log.info("connect rpc server {} on port {} success.", serviceMeta.getServiceAddr(), serviceMeta.getServicePort());
                } else {
                    log.error("connect rpc server {} on port {} failed.", serviceMeta.getServiceAddr(), serviceMeta.getServicePort());
                    future.cause().printStackTrace();
                    eventLoopGroup.shutdownGracefully();
                }
            });
            future.channel().writeAndFlush(protocol);
        }
    }
}
